package com.example.Arithmetic.Lettcode;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 日期：2024/1/3
 * 时间：10:47
 * 描述：组合总和，看有多少种组合等于目标target，回溯思想
 */
public class E01Lettcode39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> list = new ArrayList<>();
        dfs(0, candidates, target, list, new LinkedList<>());
        return list;
    }

    private void dfs(int start, int[] candidates, int target, List<List<Integer>> list, LinkedList<Integer> stack) {
        if (target==0) {
            list.add(new ArrayList<>(stack));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            int candidate = candidates[i];
//            剪枝,小于目标值没有循环必要了
            if (target<candidate){
                continue;
            }
            stack.push(candidate);
            dfs(i,candidates,target-candidate,list,stack);
            stack.pop();
        }
    }

    @Test
    public void test() {
        List<List<Integer>> lists = combinationSum(new int[]{2, 3, 6, 7}, 7);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }
}

